package com.example.clipsync;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import de.robv.android.xposed.XSharedPreferences;

/**
 * Xposed 模块主类，负责在系统启动时初始化和挂钩相关方法
 */
public class HookMain implements IXposedHookLoadPackage {
    // 日志标签
    private static final String TAG = "GlobalClipboardLS";
    // 当前模块的包名
    public static final String PACKAGE_NAME = "com.example.clipsync";

    /**
     * 当系统加载一个应用包时调用
     */
    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
        // 只在 system_server 中执行
        if (!"android".equals(lpparam.packageName)) return;

        XposedBridge.log(TAG + ": 系统服务已加载，初始化模块");

        // 使用 XSharedPreferences 读取本模块的配置
        // 在 Android 7.0+ 上 MODE_WORLD_READABLE 已被废弃
        // 需要 LSPosed 等框架支持才能正常读取
        XSharedPreferences prefs = new XSharedPreferences(PACKAGE_NAME, "ClipSync_prefs");

        // 重新加载配置，确保读取到最新值
        prefs.reload();

        // 从配置中读取开关状态
        boolean isEnabled = prefs.getBoolean("ws_enabled", false);
        if (isEnabled) {
            String url = prefs.getString("ws_url", null);
            if (url != null && !url.isEmpty()) {
                XposedBridge.log(TAG + ": 配置中 WS 已启用，启动 WebSocket 连接: " + url);
                WsManager.startOrRestart(url);
            }
        }

        // Hook ActivityManagerService 的 systemReady 方法
        // 这个方法会在系统服务准备就绪时调用
        try {
            Class<?> ams = XposedHelpers.findClass("com.android.server.am.ActivityManagerService", lpparam.classLoader);
            XposedBridge.hookAllMethods(ams, "systemReady", new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    // 获取系统上下文
                    Context systemContext = (Context) XposedHelpers.getObjectField(param.thisObject, "mContext");
                    // 注册命令广播接收器
                    registerCommandReceiver(systemContext);
                    XposedBridge.log(TAG + ": 已注册命令广播接收器");
                }
            });
        } catch (Throwable t) {
            XposedBridge.log(TAG + ": 无法 Hook ActivityManagerService.systemReady: " + t.getMessage());
        }

        // 初始化剪贴板挂钩逻辑
        ClipboardHooker.hook(lpparam.classLoader);
    }

    /**
     * 注册一个广播接收器，用于接收来自 UI 模块的命令
     */
    private void registerCommandReceiver(Context context) {
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 检查是否需要连接 WebSocket
                boolean shouldConnect = intent.getBooleanExtra("connect", false);
                if (shouldConnect) {
                    String url = intent.getStringExtra("ws_url");
                    if (url != null && !url.isEmpty()) {
                        XposedBridge.log(TAG + ": 收到连接命令，URL: " + url);
                        WsManager.startOrRestart(url);
                    }
                } else {
                    XposedBridge.log(TAG + ": 收到断开连接命令");
                    WsManager.stop();
                }
            }
        };

        // 创建意图过滤器，只接收我们关心的广播
        IntentFilter filter = new IntentFilter(MainActivity.ACTION_UPDATE_STATE);

        // 设置接收器标志位
        int receiverFlags = 0;

        // 在 Android 13 (TIRAMISU) 及以上版本，必须显式指定接收器是否导出
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            receiverFlags = Context.RECEIVER_EXPORTED;
        }

        // 注册广播接收器
        context.registerReceiver(receiver, filter, receiverFlags);
    }
}